<template>
  <div id="paramQrCode">
    <h3 class="mainTitle">参数二维码</h3>
    <div class="new-build">
      <el-button :plain="true" type="primary" @click="newQr">新建二维码</el-button>
    </div>
    <div class="searchBox">
      <el-input placeholder="二维码名称搜索" v-model="searchForm.wd" @keyup.enter.native="submitSearch">
        <el-button slot="append" @click="submitSearch">搜索</el-button>
      </el-input>
    </div>
    <div class="resultBox">
      <el-table
        v-loading="tbLoading"
        element-loading-text="拼命加载中"
        :data="qrList.list"
        @expand="handleExpand"
        stripe
        class="table"
        :row-key="row => row.id"
        :expand-row-keys="expandRows">
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="contetnWrap leftContent">
              <ul>
                <li>参数二维码：<a :href="props.row.imageUrl" download>下载二维码</a></li>
                <li>scene_id： {{ props.row.sceneStr }} 
                  <div class="qrImgWrap">
                    <img :src="props.row.imageUrl" />
                  </div>
                </li>
                <li>或发送规则名：
                  <div class="keywords">
                    <p v-if="props.row.keyword" class="cred">当前规则名：{{ props.row.keyword }}</p>
                    <p v-else-if="selKeyword[props.$index]" class="cred">当前规则名：{{ selKeyword[props.$index] }}</p>
                    <p v-else>暂无数据</p>
                    <el-select v-model="keyword[props.$index]" @change="$val => changeKeyword(props, $val)" placeholder="请选择">
                      <el-option
                        v-for="item in keywords.list"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <el-button v-if="props.row.keyword" type="danger" @click="handleDelTag(props)">删除</el-button>
                  </div>
                </li>
              </ul>
            </div>
            <div class="contetnWrap centerContent">
              <div class="editor-box">
                <editor-lite :ref="'editor'+props.row.id" :showNews="false" :editorData="props.row.reply"></editor-lite>
                <el-button type="primary" size="small" @click="handleSetReply(props.row.id)" class="btn-save">保存回复</el-button>
              </div>
            </div>
            <div class="contetnWrap rightContent">
              <h3>给粉丝打标签：</h3>
              <div class="tag-box" v-if="props.row.tags.length > 0">
                <el-tag
                  :key="tag.tagName"
                  v-for="tag in props.row.tags"
                  :closable="true"
                  :close-transition="false"
                  @close="handleFansTagDel(props, tag)"
                >
                {{ tag.tagName }}
                </el-tag>
              </div>
              <div class="tag-box" v-else>
                暂无标签
              </div>
              <div class="add-tag">
                <el-select v-model="tempTagItem[props.$index]" @change="$val => addFansTag(props, $val)" placeholder="请选择">
                  <el-option
                    v-for="item in tagList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="二维码名称" className="is-center">
           <template slot-scope="scope">
             {{scope.row.name}}
           </template>
        </el-table-column>
        <el-table-column label="创建时间" className="is-center">
           <template slot-scope="scope">
             {{$date.format(scope.row.createTime, 'YYYY-MM-DD HH:mm:ss')}}
           </template>
        </el-table-column>
        <el-table-column label="操作" className="is-center">
           <template slot-scope="scope">
              <el-button v-if="scope.row.status" type="success" size="small" @click="handleClose(scope.row)">关闭</el-button>
              <el-button v-else type="danger" size="small" @click="handleActive(scope.row)">启用</el-button>
              <el-button size="small" @click="expandRow(scope.row.id)">编辑</el-button>
           </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="searchForm.page"
        :page-size.sync="searchForm.size"
        layout="total, prev, pager, next, jumper"
        :total="qrList.page.total"
        @current-change="initPageData()">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {mapMutations, mapState, mapActions} from 'vuex'
  import editorLite from '@/components/common/content/wechatEditorLite2'
  export default {
    data () {
      return {
        appid: this.$route.params.appid,
        searchForm: {
          appid: this.$route.params.appid,
          wd: '',
          page: 1,
          size: 10
        },
        tbLoading: false,
        isSave: false,
        keyword: new Array(10),
        tagsList: [],
        tempTagItem: new Array(10),
        selKeyword: new Array(10),
        expandRows: []
      }
    },
    components: {editorLite},
    computed: {
      ...mapMutations(['UPDATE_SUBSCRIBE_REPLY', 'SET_SOURCE_INFO', 'INIT_SOURCE_INFO']),
      ...mapState({
        qrList: state => state.qrcodeList.qrList,
        keywords: state => state.qrcodeList.keywordList,
        tagList: state => state.qrcodeList.tagsList,
        subscribeReply: state => state.qrcodeList.subscribeReply,
        sourceInfo: state => state.qrcodeList.sourceInfo
      })
    },
    mounted () {
      this.initPageData()
    },
    watch: {
      sourceInfo: {
        deep: true,
        handler: function (obj) {
          this.UPDATE_SUBSCRIBE_REPLY({mediaid: obj.mediaid, msgType: obj.msgType})
        }
      }
    },
    methods: {
      ...mapActions(['getQrList', 'newQrCode', 'switchActiveStatus', 'getKeywordReply', 'getKwList', 'setQrKeyword', 'delQrKeyword', 'getQrKeyword', 'getTagList', 'addQrTags', 'delQrTags', 'getQrReply', 'setQrReply']),
      expandRow (id) {
        if (this.expandRows.indexOf(id) === -1) {
          this.expandRows.push(id)
        }
      },
      initPageData () {
        this.getqrlist()
        this.getKeywordList()
        this.getTagsList()
      },
      initTable () {
        this.submitSearch()
          .finally((res) => { this.tbLoading = false })
      },
      // 获取二维码
      getqrlist (item) {
        this.getQrList({ ...this.searchForm })
      },
      // 新建二维码
      newQr () {
        let _this = this
        let getBLen = function (str) { // 判断输入字符长度
          if (typeof str !== 'string') {
            str += ''
          }
          return str.replace(/[^\x00-\xff]/g, '01').length
        }
        this.$prompt('请输入二维码名称(最长为50个汉字/100个英文字母)', '新建二维码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/,
          inputErrorMessage: '请正确输入内容！',
          beforeClose: function (action, instance, done) {
            if (action === 'confirm') {
              if (getBLen(instance.inputValue) > 100) {
                _this.$message({
                  type: 'info',
                  message: '输入文字已超出，请重新输入！'
                })
                return false
              } else {
                done()
              }
            } else {
              done()
            }
          },
          callback: function (action, instance) {
            if (action === 'confirm') {
              // 确定
              _this.newQrCode({
                appid: _this.appid,
                wd: instance.inputValue
              }).then((res) => {
                if (res.data.code === 3) {
                  _this.$message({
                    type: 'info',
                    message: res.data.msgZ
                  })
                  return false
                }
                _this.submitSearch()
                _this.selKeyword = []
                _this.$message({
                  type: 'success',
                  message: '创建成功！'
                })
              })
            } else {
              // 取消
              /* _this.$message({
                type: 'info',
                message: '取消创建！'
              }) */
            }
          }
        })
      },
      // 搜索二维码
      submitSearch  () {
        this.tbLoading = true
        this.getQrList({ ...this.searchForm })
          .finally((res) => { this.tbLoading = false })
      },
      // 启用
      handleActive (row) {
        this.switchActiveStatus({
          qrId: row.id,
          status: 1
        })
        row.status = 1
      },
      handleClose (row) {
        this.switchActiveStatus({
          qrId: row.id,
          status: 0
        })
        row.status = 0
      },
      // 更改关键词
      changeKeyword (prop, value) {
        let temp = this.keywords.list.filter((item) => {
          return item.id === value
        })
        prop.row.keyword = temp[0].name
        this.selKeyword.splice(prop.$index, 1, temp[0].name)
        // prop.row.keyword = this.keyword
        /* this.selKeyword[prop.$index] = temp[0].keywords
        this.selKeyword = [].concat(this.selKeyword) */
        this.setQrKeyword({
          qrId: prop.row.id,
          keywordId: value
        })
      },
      // 删除关键词
      handleDelTag (props) {
        this.delQrKeyword({ qrId: props.row.id })
        props.row.keyword = ''
        this.selKeyword.splice(props.$index, 1)
        this.getKwList(this.appid)
      },
      // 获取关键词
      getQrKeyword () {
        // let _this = this
        // let kwlist = this.qrList.list
      },
      // 获取关键词列表
      getKeywordList () {
        this.getKwList(this.appid)
      },
      getTagsList () {
        this.getTagList(this.appid)
      },
      // 添加标签
      addFansTag (props, val) {
        let temp = this.tagList.filter((item) => {
          return item.id === val
        })
        function TagObj (creatTime, id, qrId, status, tagId, tagName) {
          this.creatTime = creatTime
          this.id = id
          this.qrId = qrId
          this.status = status
          this.tagId = tagId
          this.tagName = tagName
        }
        let NewTag = new TagObj(props.row.createTime, 0, props.row.id, 1, temp[0].id, temp[0].name)
        // console.log(props.row.tags)
        let _this = this
        for (let i = 0; i < props.row.tags.length; i++) {
          if (props.row.tags[i].tagName === NewTag.tagName) {
            _this.$message({
              type: 'info',
              message: '此标签已存在！'
            })
            return false
          }
        }
        props.row.tags.push(NewTag)
        this.addQrTags({
          qrId: props.row.id,
          tagId: temp[0].id,
          tagName: temp[0].name
        })
        _this.$message({
          type: 'success',
          message: '标签添加成功！'
        })
      },
      // 删除标签
      handleFansTagDel (props, tag) {
        props.row.tags.splice(props.row.tags.indexOf(tag), 1)
        // console.log(tag.qrId, tag.tagId)
        this.delQrTags({
          qrId: tag.qrId,
          tagId: tag.tagId
        })
        this.$message({
          type: 'success',
          message: '标签已删除！'
        })
      },
      // 展开行
      handleExpand (row, expanded) {
        if (expanded) {
          this.getQrReply(row.id)
        } else {
          this.expandRows = this.expandRows.filter(item => item !== row.id)
        }
      },
      // 设置回复
      async handleSetReply (qrId) {
        const $editor = this.$refs['editor' + qrId]
        const res = await this.setQrReply({
          ...$editor.getContent,
          content: $editor.$el.querySelector('.editor-text').innerHTML,
          appid: this.$route.params.appid,
          qrId: qrId
        })
        if (res.data.code === 1) {
          this.$message.success('保存成功')
        }
      }
    }
  }
</script>

<style lang="scss">
  #paramQrCode{
    .el-input-group__append .el-button{
      color: #333;
    }
    .mainTitle{
      font-size: 16px;
      font-weight: normal;
      border-bottom: 1px solid #ccc;
      padding-bottom: 15px;
      margin-bottom: 20px;
    }
    .new-build{float: left;}
    .searchBox{
      width: 300px;
      margin: 0 0 20px 20px;
      float: left;
    }
    .btn{
      border:1px solid #ccc;
    }
    .btn-success{
      background: green;
    }
    .btn-warning{
      background: red;
    }
  }
  .contetnWrap{
    float: left;
    color: #99a9bf;
    margin:0;
    min-height: 300px;
    .el-form-item{
      margin:0;
    }
    .edit-status{
      float: left;
      padding:0 5px;
    }
    .edit-type{
      font-size: 14px;
    }
    .editor-box .btn-save{float:right;margin-top:15px;}
  }
  .leftContent{
    width:24%;
    border-right: 1px dashed #ccc;
    .qrImgWrap{
      margin: 0 auto 15px;
      img{
        width: 200px;
      }
    }
    .keywords{
      width:85%;
      float: left;
      .el-select{
        width: 120px;
        margin-right: 5px;
      }
      p{
        padding:5px 0;
        margin: 12px 0;
        border-top: 1px dashed #ccc;
        border-bottom: 1px dashed #ccc;
      }
      p.cred{color: #f00;}
      span{
        margin:0 3px;
      }
    }
    .inputkeywords{
      width:85%;
      float: left;
      input{
        width:120px;
      }
    }
  }
  .centerContent{
    width:48%;
    margin: 0 15px;
    border-right: 1px dashed #ccc;
    .editor-box{
      width:95%;
      margin: 0 0 0 10px;
      .wxEditLite{
        margin-bottom: 15px;
      }
    }
  }
  .rightContent{
    width:24%;
    h3{
      font-size: 14px;
      font-weight: normal;
      color: #666;
    }
    .tag-box{
      font-size: 14px;
      color: #666;
      padding: 8px 0;
      margin: 8px 0;
      border-top: 1px dashed #ccc;
      border-bottom: 1px dashed #ccc;
      span{
        margin: 0 5px 5px 0;
      }
    }
    .add-tag{
      input{width: 150px;}
    }
  }
</style>
